const { Controller } = require('egg');

class ClientController extends Controller {
  async validateProject() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const result = await this.app.mysql.query(`select * from project where id = ?`, [id]);
    if (result.length === 0) {
      ctx.body.retCode = -1;
    }
  }

  async getModelFunction() {
    const { ctx } = this;
    const { id } = ctx.request.body;

    const { func, funcLock } = (
      await this.app.mysql.query(`select func,funcLock from project where id = ?`, [id])
    )[0];
    if (funcLock) {
      ctx.body.retCode = -1;
    } else {
      ctx.body.content = func ? JSON.parse(func) : [];
      this.app.mysql.query(`update project set funcLock=1 where id=?`, [id]);
    }
  }

  async saveModelFunction() {
    const { ctx } = this;
    const { functiontable, id } = ctx.request.body;
    this.app.mysql.query(
      `update project set func=?,funcLock=0,funcMergedCount=funcMergedCount+1 where id=?`,
      [JSON.stringify(functiontable), id]
    );
  }

  async getModelModule() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const { module, moduleLock } = (
      await this.app.mysql.query(`select module,moduleLock from project where id = ?`, [id])
    )[0];
    if (moduleLock) {
      ctx.body.retCode = -1;
    } else {
      ctx.body = { component: module ? JSON.parse(module) : [] };
      this.app.mysql.query(`update project set moduleLock=1 where id=?`, [id]);
    }
  }

  async saveModelModule() {
    const { ctx } = this;
    const { component, id } = ctx.request.body;
    await this.app.mysql.query(
      `update project set module=?,moduleLock=0,moduleMergedCount=moduleMergedCount+1 where id=?`,
      [JSON.stringify(component), id]
    );
  }
}

module.exports = ClientController;
